import { cloneDeep } from "lodash-es";
import { AppRouteRecordRaw } from "../types";
const Layout = () => import("@/layouts/index.vue");

const LayoutMap = new Map<string, any>();

LayoutMap.set("LAYOUT", Layout);

let dynamicViewsModules: Record<string, () => Promise<Recordable>>;

const dynamicImport = (
  dynamicViewsModules: Record<string, () => Promise<Recordable>>,
  component: string
) => {
  const keys = Object.keys(dynamicViewsModules);
  const matchKeys = keys.filter((key) => {
    const k = key.replace("../../views", "");
    const startFlag = component.startsWith("/");
    const endFlag = component.endsWith(".vue") || component.endsWith(".tsx");
    const startIndex = startFlag ? 0 : 1;
    const lastIndex = endFlag ? k.length : k.lastIndexOf(".");
    return k.substring(startIndex, lastIndex) === component;
  });
  if (matchKeys?.length === 1) {
    const matchKey = matchKeys[0];
    return dynamicViewsModules[matchKey];
  } else if (matchKeys?.length > 1) {
    console.error(
      "Please do not create `.vue` and `.TSX` files with the same file name in the same hierarchical directory under the views folder. This will cause dynamic introduction failure"
    );
    return;
  }
};
export const asyncImportRoute = (routes: AppRouteRecordRaw[] | undefined) => {
  if (!dynamicViewsModules) {
    dynamicViewsModules = import.meta.glob("../../views/**/*.{vue,tsx}");
  }

  if (!routes) return;
  routes.forEach((item) => {
    let { component } = item;
    const { children } = item;
    if (component) {
      console.log("dynamicImport(dynamicViewsModules, component)");
      console.log(dynamicImport(dynamicViewsModules, component));
      item.component = dynamicImport(dynamicViewsModules, component);
    }
    children && asyncImportRoute(children);
  });
};

export const transformToRoute = (routeList: any[]) => {
  routeList.forEach(async (route) => {
    const component = route.component as string;
    if (component) {
      if (route.children && route.children.length > 0) {
        route.children = [cloneDeep(route)];
        route.component = LayoutMap.get(component.toUpperCase());
      } else {
        route.children = [cloneDeep(route)];
        route.component = Layout;
        route.name = `${route.name}Parent`;
        route.path = "";
        const meta = route.meta || {};
        meta.single = true;
        meta.affix = false;
        route.meta = meta;
      }
      route.children && asyncImportRoute(route.children);
    } else {
      console.error("请正确配置路由：" + route?.name + "的component属性");
    }
  });

  return routeList;
};
